import { computed, defineComponent, ref, ComponentPublicInstance } from 'vue'
import { sysRole } from '@/api/setting'
import { getUser, assignRoles } from '@/api/employees'
import { message } from 'ant-design-vue'
import usePagination from '@/hooks/usePagination'

type ExposeProps = {
  mode: string
  formState: any
  handleVisible: (id: string) => void
}

export type ModelType = ComponentPublicInstance<ExposeProps>

type CheckboxDataT = {
  id: string
  roleIds: string[]
}

export default defineComponent({
  name: 'Model',
  emits: ['run'],
  setup(props, { expose }) {
    const visible = ref(false)
    const checkboxData = ref<CheckboxDataT>({
      id: '',
      roleIds: []
    })

    const { dataSource } = usePagination(sysRole, {
      formatResult: (res: any) => res.data.rows,
      pagination: {
        pageSize: 999,
        currentKey: 'page',
        pageSizeKey: 'pagesize'
      }
    })

    const checkedCom = computed(() =>
      dataSource.value.map((item: any) => (
        <a-col span="4">
          <a-checkbox value={item.id}>{item.name}</a-checkbox>
        </a-col>
      ))
    )

    async function handleOk() {
      const res = await assignRoles(checkboxData.value)
      message.success(res.message)
      visible.value = false
    }

    function handlenCancel() {
      // 关闭弹窗
      visible.value = false
    }

    function handlenAfterClose() {
      // 关闭弹窗后
      visible.value = false
    }

    async function handleVisible(id: string) {
      visible.value = true
      checkboxData.value.id = id
      const res = (await getUser(id)) as any
      checkboxData.value.roleIds = res.data.roleIds
    }

    expose({
      handleVisible
    })

    return () => (
      <>
        <a-modal
          v-model:visible={visible.value}
          title="编辑"
          style="width: 800px"
          onOk={handleOk}
          onCancel={handlenCancel}
          afterClose={handlenAfterClose}
        >
          <a-checkbox-group
            v-model:value={checkboxData.value.roleIds}
            style="width: 100%"
          >
            <a-row>{checkedCom.value}</a-row>
          </a-checkbox-group>
        </a-modal>
      </>
    )
  }
})
